package com.dm.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dm.common.JsonResult;
import com.dm.entity.Room;
import com.dm.entity.Student;
import com.dm.service.IRoomService;
import com.dm.service.IStudentService;
import com.dm.utils.ExcelUtil;
import com.dm.utils.MapBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dancun
 * @since 2021-05-02
 */
@RestController
@RequestMapping("/student")
@Slf4j
public class StudentController {
    @Autowired
    IStudentService studentService;

    @Autowired
    IRoomService roomService;

    @PostMapping("/save")
    @ApiOperation("")
    public JsonResult save(@RequestBody Student student){
        try{
            studentService.save(student);
        }catch (Exception e){
            log.info(e.getStackTrace().toString());
            return JsonResult.renderError();
        }
        return JsonResult.renderSuccess();
    }
    @PostMapping("/delete")
    @ApiOperation("")
    public JsonResult delete(@RequestBody Student student){
        try{
            studentService.removeById(student.getScode());
        }catch (Exception e){
            log.info(e.getStackTrace().toString());
            return JsonResult.renderError();
        }
        return JsonResult.renderSuccess();
    }
    @PostMapping("/update")
    @ApiOperation("")
    public JsonResult update(@RequestBody Student student){
        try{
            studentService.updateById(student);
        }catch (Exception e){
            log.info(e.getStackTrace().toString());
            return JsonResult.renderError();
        }
        return JsonResult.renderSuccess();
    }

    @PostMapping("/list")
    @ApiOperation("")
    public JsonResult List(@RequestBody JSONObject jsonObject){
        Integer pageSize =null;
        Integer pageNum =null;

        try{
            pageSize = Integer.parseInt(jsonObject.getString("pageSize"));
            pageNum = Integer.parseInt(jsonObject.getString("pageNum"));
        }catch (Exception e){
            e.printStackTrace();
        }
        if(pageSize!=null&&pageSize!=0){
            if (pageNum==null){
                pageSize=10;
            }
            PageHelper.startPage(pageNum,pageSize);
        }
        PageInfo page = null;

        try{
            page = new PageInfo<Student>(studentService.listStudent(Wrappers.query()));
        }catch (Exception e){
            log.info(e.getStackTrace().toString());
            return JsonResult.renderError();
        }
        return JsonResult.renderSuccess(page);
    }

    @PostMapping("/search")
    @ApiOperation("")
    public JsonResult search(@RequestBody JSONObject jsonObject){
        String key ="";
        List<Student> list = new ArrayList<>();

        try{
            key = jsonObject.getString("key");

        }catch (Exception e){
            e.printStackTrace();
        }


        try{
            QueryWrapper<Student> wrapper = Wrappers.query();
            if (key!=null && key !="" && !key.equals("")){
                wrapper.lambda().like(Student::getScode,key).or().like(Student::getName,key);
            }
            list = studentService.listStudent(wrapper);
        }catch (Exception e){
            log.info(e.getStackTrace().toString());
            return JsonResult.renderError();
        }
        return JsonResult.renderSuccess(list);
    }

    @PostMapping("/find")
    @ApiOperation("")
    public JsonResult find(@RequestBody Integer id){
        Student student = null;
        try{
            student = studentService.getOneStudent(id);
        }catch (Exception e){
            log.info(e.getStackTrace().toString());
            return JsonResult.renderError();
        }
        return JsonResult.renderSuccess(student);
    }

    @PostMapping(value = "/getExcelData",produces = "application/json;charset=utf-8")
    public JsonResult getExcelData(MultipartFile file) {
        List<Map<String,Object>> errorMap = new ArrayList<>();

        try {
            List<List<Object>> lists = ExcelUtil.getUserListByExcel(file.getInputStream(), file.getOriginalFilename());
            //List<List<Object>>--->List<User>
            List<Map<String,Object>> list = new ArrayList<>();
            List<String> tag = new ArrayList<>();
            //
            for(int i =0;i<lists.get(0).size();i++){
                String t=String.valueOf(lists.get(0).get(i));
                switch (t){
                    case "学号":
                        tag.add("scode");
                        break;
                    case "姓名":
                        tag.add("name");
                        break;
                    case "性别":
                        tag.add("sex");
                        break;
                    case "联系方式":
                        tag.add("tel");
                        break;
                    case "宿舍楼":
                        tag.add("did");
                        break;
                    case "寝室号":
                        tag.add("rid");
                        break;
                    case "床号":
                        tag.add("bedid");
                        break;

                    default:
                        return JsonResult.renderError("表头格式错误,请下载模板对照");
                }
            }

//            switch (list);
            for (int i = 1; i < lists.size(); i++) {
                Map<String,Object> map = new HashMap<>();
                for(int x =0;x<lists.get(0).size();x++){

                    map.put(tag.get(x),String.valueOf(lists.get(i).get(x)));
                }

//                map.put("pwd", DigestUtils.md5DigestAsHex(map.get("pwd").getBytes()));

                try {
                    LambdaQueryWrapper<Room> roomLambdaQueryWrapper = Wrappers.lambdaQuery();
                    roomLambdaQueryWrapper.eq(Room::getDid,map.get("did")).eq(Room::getRid,map.get("rid"));
                    try{
                        map.put("rid",roomService.list(roomLambdaQueryWrapper).get(0).getId());
                        map.put("bedid",Integer.parseInt(map.get("bedid").toString()));
                        map.put("rid",Integer.parseInt(map.get("rid").toString()));
                    }catch (Exception e){
                        e.printStackTrace();
                        map.put("errer","寝室不存在");

                        errorMap.add(map);
                        continue;
                    }

                    LambdaQueryWrapper<Student> wrapper = Wrappers.lambdaQuery();
                    wrapper.eq(Student::getRid,map.get("rid")).eq(Student::getBedid,map.get("bedid"));
                    if(studentService.list(wrapper).size()==0){
                        int getGalleryful = roomService.getById(Integer.parseInt(map.get("rid").toString())).getGalleryful();//寝室容纳量
                        if(Integer.parseInt(map.get("bedid").toString())<=getGalleryful){
                            map.remove("did");
                            Student stu = new Student();
                            stu=MapBean.<Student>mapToBean(map,stu.getClass());
                            studentService.saveOrUpdate(stu);
                        }else{
                            map.put("error","没有此床铺");
                            errorMap.add(map);
                            continue;
                        }

                    }else{
                        map.put("errer","床铺已住人");
                        errorMap.add(map);
                        continue;
                    };
//                teacherDao.insertByList(list);
//                    issuccess=true;
                }catch (Exception e){
                    e.printStackTrace();
                    map.put("errer","头格式错误,请下载模板对照");
                    errorMap.add(map);
                    continue;
//                    return "{\"state':\"0\",\"message\":\"表头格式错误,请下载模板对照\"}";
                }
            }




            //插入数据
//            userInfoService.insert(users);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.renderError("表头格式错误,请下载模板对照");
        }
//        UserInfoExample userExample = new UserInfoExample();
//        List<UserInfo> allusers = userInfoService.selectByExample(userExample);
//        model.addAttribute("all", allusers);
        if(errorMap.size()!=0)
            return JsonResult.renderSuccess("部分导入失败",errorMap);

        return JsonResult.renderSuccess("导入成功");
    }


}
